"""Ingress资源Markdown写入器模块"""

from typing import Dict, Any, List
from src.writers.base import Writer
from src.utils.markdown_builder import MarkdownBuilder

class IngressWriter(Writer):
    """
    Ingress资源Markdown写入器
    负责将提取的Ingress资源信息写入Markdown文件
    """
    
    def write(self, data: Dict[str, Any], output_path: str) -> None:
        """
        将提取的Ingress信息写入Markdown
        
        Args:
            data: 提取的Ingress信息
            output_path: 输出文件路径
        """
        if not data or data.get("kind") != "Ingress":
            self.logger.warning(f"无效的Ingress数据: {data.get('name', '未知')}")
            return
        
        # 创建Markdown构建器
        md = self.create_markdown_builder()
        
        # 收集节标题，用于生成目录
        sections = ["基本信息", "访问规则", "TLS配置"]
        if data.get("default_backend"):
            sections.append("默认后端")
        
        # 标题
        md.header(f"Ingress: {data.get('name', '未知')}", 1)
        
        # 命名空间
        md.bold("命名空间:").text(f" {data.get('namespace', 'default')}").newline(2)
        
        # 目录
        if len(sections) > 2:  # 只有当节较多时才添加目录
            md.toc(sections)
        
        # 基本信息
        self._write_basic_info(md, data)
        
        # 访问规则
        self._write_rules(md, data)
        
        # TLS配置
        self._write_tls_config(md, data)
        
        # 默认后端
        if data.get("default_backend"):
            self._write_default_backend(md, data)
        
        # 生成Markdown文件
        self.write_markdown(md, output_path)
    
    def _write_basic_info(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入基本信息
        
        Args:
            md: Markdown构建器
            data: Ingress数据
        """
        md.header("基本信息", 2)
        
        # 基本元数据表
        basic_info = {
            "名称": data.get("name", ""),
            "命名空间": data.get("namespace", "default"),
            "创建时间": data.get("creation_timestamp", ""),
            "Ingress类": data.get("ingress_class_name", "")
        }
        md.dict_table(basic_info)
        
        # 标签和注解
        if data.get("labels"):
            md.header("标签", 3)
            md.dict_table(data.get("labels", {}))
        
        if data.get("annotations"):
            md.header("注解", 3)
            md.dict_table(data.get("annotations", {}))
    
    def _write_rules(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入访问规则
        
        Args:
            md: Markdown构建器
            data: Ingress数据
        """
        md.header("访问规则", 2)
        
        rules = data.get("rules", [])
        if not rules:
            md.paragraph("未配置访问规则")
            return
        
        # 遍历每条规则
        for i, rule in enumerate(rules):
            host = rule.get("host", "*")
            md.header(f"规则 {i+1}: {host}", 3)
            
            paths = rule.get("http", {}).get("paths", [])
            if not paths:
                md.paragraph("此规则没有配置路径")
                continue
                
            # 创建路径表格
            headers = ["路径", "路径类型", "后端服务", "端口", "端口名称"]
            rows = []
            
            for path in paths:
                path_value = path.get("path", "/")
                path_type = path.get("path_type", "Prefix")
                
                backend = path.get("backend", {})
                
                # 处理新版API的后端结构
                if "service" in backend:
                    service = backend.get("service", {})
                    service_name = service.get("name", "")
                    
                    port = service.get("port", {})
                    port_number = port.get("number", "")
                    port_name = port.get("name", "")
                else:
                    # 处理旧版API的后端结构
                    service_name = backend.get("service_name", "")
                    port_number = backend.get("service_port", "")
                    port_name = ""
                
                rows.append([
                    path_value,
                    path_type,
                    service_name,
                    str(port_number),
                    port_name
                ])
            
            md.table(headers, rows)
    
    def _write_tls_config(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入TLS配置
        
        Args:
            md: Markdown构建器
            data: Ingress数据
        """
        md.header("TLS配置", 2)
        
        tls = data.get("tls", [])
        if not tls:
            md.paragraph("未配置TLS")
            return
        
        # 创建TLS配置表格
        headers = ["主机", "密钥名称"]
        rows = []
        
        for tls_entry in tls:
            hosts = tls_entry.get("hosts", [])
            secret_name = tls_entry.get("secret_name", "")
            
            # 如果有多个主机，为每个主机创建一行
            if hosts:
                for host in hosts:
                    rows.append([host, secret_name])
            else:
                rows.append(["*", secret_name])
        
        md.table(headers, rows)
    
    def _write_default_backend(self, md: MarkdownBuilder, data: Dict[str, Any]) -> None:
        """
        写入默认后端信息
        
        Args:
            md: Markdown构建器
            data: Ingress数据
        """
        md.header("默认后端", 2)
        
        backend = data.get("default_backend", {})
        
        # 处理新版API的后端结构
        if "service" in backend:
            service = backend.get("service", {})
            service_name = service.get("name", "")
            
            port = service.get("port", {})
            port_number = port.get("number", "")
            port_name = port.get("name", "")
            
            backend_info = {
                "服务名称": service_name,
                "端口号": port_number
            }
            
            if port_name:
                backend_info["端口名称"] = port_name
        else:
            # 处理旧版API的后端结构
            service_name = backend.get("service_name", "")
            port_number = backend.get("service_port", "")
            
            backend_info = {
                "服务名称": service_name,
                "端口号": port_number
            }
        
        md.dict_table(backend_info)